# -*- coding: utf-8 -*-
"""
@Time   :  2024/08/07 22:26
@Author :  Dilee
"""
import os
import uuid
from dataclasses import dataclass

from injector import inject
from openai import OpenAI

from internal.exception import FailException
from internal.schema.app_schema import CompletionReq
from internal.service import AppService
from pkg.response import success_json, validate_error_json, success_message


@inject
@dataclass
class AppHandler:
    """应用控制器"""
    app_service: AppService

    def delete_app(self, aid: uuid.UUID):
        app = self.app_service.delete_app(aid)
        return success_message(f"删除成功,name为:{app.name}")

    def update_app(self, aid: uuid.UUID):
        app = self.app_service.update_app(aid)
        return success_message(f"更新成功,name为:{app.name}")

    def get_app(self, aid: uuid.UUID):
        app = self.app_service.get_app(aid)
        return success_message(f"获取成功,name为:{app.name}")

    def create_app(self):
        """调用服务创建新的app记录"""
        app = self.app_service.create_app()
        return success_message(f"创建成功,id为:{app.id}")

    def completion(self):
        req = CompletionReq()
        if not req.validate():
            return validate_error_json(req.errors)

        # 2.调用openai接口
        client = OpenAI(base_url=os.getenv("OPENAI_API_BASE"))

        completion = client.chat.completions.create(
            model="gpt-3.5-turbo-16k",
            messages=[
                {"role": "system", "content": "你是OpenApi开发的机器人，根据用户的提问，回答用户的问题。"},
                {"role": "user", "content": req.query.data}
            ]
        )

        # 3.返回数据
        content = completion.choices[0].message.content
        return success_json({"content": content})

    def ping(self):
        raise FailException("数据未找到")
        # return success_json({"content": "pong"})
